package org.exmaple;

/**
 * 修饰一个静态的方法
 * Sync1和Sync2是Sync的两个对象，但在thread1和thread2并发执行时却保持了线程同步。这是因为run中调用了静态方法method，而静态方法是属于类的，所以Sync1和Sync2相当于用了同一把锁
 */
public class Test4 {
    public static void main(String args[]){
        Sync Sync1 = new Sync();
        Sync Sync2 = new Sync();
        Thread thread1 = new Thread(Sync1, "Sync1");
        Thread thread2 = new Thread(Sync2, "Sync2");
        thread1.start();
        thread2.start();
    }
}

/**
 * 同步线程
 */
class Sync implements Runnable {
    private static int count;

    public Sync() {
        count = 0;
    }

    public synchronized static void method() {
        for (int i = 0; i < 5; i ++) {
            try {
                System.out.println(Thread.currentThread().getName() + ":" + (count++));
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void run() {
        method();
    }
}
